package org.fungene.services.kegg;

import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import keggapi.KEGGLocator;
import keggapi.KEGGPortType;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class KEGGMapLauncher {
	
	private String pathway;
	private String[] KEGGIDs;

	public KEGGMapLauncher() {
		super();
	}

	public KEGGMapLauncher(String[] args) {
		super();
		pathway = args[0];
		KEGGIDs = args[1].split(";");
	}
	
	public String launch() {
		try {
			KEGGLocator locator = new KEGGLocator();
			KEGGPortType keggServer = locator.getKEGGPort();
			// 对每个Pathway获取染色后的URL
			System.out.println("pathway: " + pathway);
			// 字体颜色
			String[] fg_list = { "gray" };
			// 背景颜色
			String[] bg_list = { "#ff00ff" };
			String URL = keggServer.get_html_of_colored_pathway_by_objects(
					pathway, KEGGIDs, fg_list, bg_list);
//			System.out.println(URL);
			String imageWithMap = getImageMap(URL);
//			System.out.println(imageWithMap);
			return imageWithMap;
		} catch (ServiceException e1) {
			e1.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private String getImageMap(String URL) {
		try {
			HttpClient httpClient = new HttpClient();
			GetMethod get = new GetMethod(URL);
			httpClient.executeMethod(get);
			String HTML = get.getResponseBodyAsString();
//			System.out.println(HTML);
			int beginIndex = HTML.indexOf("<img src=\"/tmp/mark_pathway_www");
			int endIndex = HTML.indexOf("</map>") + "</map>".length();

			return HTML.substring(beginIndex, endIndex).replaceAll("\"/",
					"\"http://www.genome.jp/");
		} catch (Exception ex) {
			System.out.println("ERROR");
			return "";
		}
	}
}
